package cn.net.xyan.blossom.core.support

import org.hibernate.HibernateException
import org.hibernate.engine.spi.SessionImplementor
import org.hibernate.id.enhanced.TableGenerator
import org.hibernate.service.ServiceRegistry
import org.hibernate.type.LongType
import org.hibernate.type.Type

import java.io.Serializable
import java.text.SimpleDateFormat
import java.util.*

open class TableSequenceGenerator : TableGenerator() {
    /**
     * read configuration parameters
     */
    override fun configure(
            type: Type, params: Properties,  serviceRegistry: ServiceRegistry) {

        params.put(TableGenerator.CONFIG_PREFER_SEGMENT_PER_ENTITY, true)

        super.configure(LongType.INSTANCE, params, serviceRegistry)

    }

    /**
     * get super value and format it
     */
    @Synchronized @Throws(HibernateException::class)
    override fun generate(
            session: SessionImplementor, `object`: Any?): Serializable {
        val generated = super.generate(session, `object`) as Long
        //val now = Date()
        //val df = SimpleDateFormat("yyyyMMddHHmmss")

        //val dateStr = df.format(now)

        return "%012d".format(generated)

    }

    companion object {
        //@JvmField
        const val STRATEGY = "cn.net.xyan.blossom.core.support.TableSequenceGenerator"
    }
}

class DateTableSequenceGenerator : TableSequenceGenerator() {


    /**
     * get super value and format it
     */
    @Synchronized @Throws(HibernateException::class)
    override fun generate(
            session: SessionImplementor, `object`: Any?): Serializable {
        val generated = super.generate(session, `object`) as String
        val now = Date()
        val df = SimpleDateFormat("yyyyMMddHHmmss")

        val dateStr = df.format(now)

        return "%s%s".format(dateStr,generated)

    }

    companion object {
        //@JvmField
        const val STRATEGY = "cn.net.xyan.blossom.core.support.DateTableSequenceGenerator"
    }
}
